<template>
  <div class="app-container">
    <sticky class="filter-container">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-input
            v-model="listSearch.search"
            placeholder="搜索"
            style="margin-right: 3px;width: 200px"
            class="filter-item"
            size="mini"
            clearable
            @keyup.enter.native="handleSearch"
            @clear="handleSearch"
            @blur="handleSearch"
          />
          <el-select
            v-model="listSearch.is_active"
            placeholder="状态"
            clearable
            class="filter-item"
            size="mini"
            style="margin-right: 10px;width: 80px"
            @change="handleSearch"
          >
            <el-option
              v-for="item in enabledTypeOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
          <el-button
            v-waves
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-search"
            @click="handleSearch"
          >
            搜索
          </el-button>
          <el-button
            v-waves
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-refresh-right"
            :loading="refreshLoading"
            @click="refresh"
          />
        </el-col>
        <el-col :span="8" style="text-align: right">
          <el-dropdown v-if="checkPermission(['admin', 'user_all', 'user_export'])" trigger="click">
            <el-button
              v-waves
              :loading="downLoading"
              class="filter-item"
              size="mini"
              type="primary"
              icon="el-icon-download"
              style="margin-right: 10px;"
            >
              导出
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="handleDownloadCurrent">导出当前</el-dropdown-item>
              <el-dropdown-item @click.native="handleDownloadAll">导出所有</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            v-if="checkPermission(['admin','user_all', 'user_create'])"
            v-waves
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="showAdd"
          >
            新增
          </el-button>
        </el-col>
      </el-row>
    </sticky>
    <!-- 表格渲染 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      :default-sort="{ prop: '-date_joined', order: 'descending' }"
      @sort-change="sortChange"
    >
      <el-table-column label="头像" width="60px">
        <template slot-scope="scope">
          <el-avatar shape="square" :size="35" :src="url_api + scope.row.avatar" />
        </template>
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名"
        width="100px"
      />
      <el-table-column
        prop="name"
        label="姓名"
        width="80px"
      />
      <el-table-column
        prop="email"
        label="邮箱地址"
      />
      <el-table-column
        prop="mobile"
        label="手机号码"
        width="130px"
      />
      <el-table-column
        prop="department_name"
        label="组织"
      />
      <el-table-column
        prop="position"
        label="岗位"
      />
      <el-table-column
        prop="date_joined"
        label="加入时间"
        sortable="custom"
      />
      <el-table-column label="状态" width="70px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_active ? 'success':'danger'">{{ scope.row.is_active ? '激活':'锁定' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="150px"
        align="center"
      >
        <template slot-scope="scope">
          <el-tooltip v-if="checkPermission(['admin','user_all','user_list'])" class="item" effect="dark" content="详情" placement="top">
            <el-button
              type="text"
              icon="el-icon-view"
              @click="showView(scope.row.id)"
            />
          </el-tooltip>
          <el-tooltip v-if="checkPermission(['admin','user_all','user_edit'])" class="item" effect="dark" content="编辑" placement="top">
            <el-button
              type="text"
              icon="el-icon-edit"
              :disabled="scope.row.id === id"
              @click="showEdit(scope.row.id)"
            />
          </el-tooltip>
          <el-tooltip v-if="checkPermission(['admin','user_all'])" class="item" effect="dark" content="重置密码" placement="top">
            <el-button
              type="text"
              icon="el-icon-link"
              :disabled="scope.row.id === id"
              @click="setPassword(scope.row)"
            />
          </el-tooltip>
          <el-tooltip v-if="checkPermission(['admin','user_all','user_delete'])" class="item" effect="dark" content="删除" placement="top">
            <el-button
              type="text"
              icon="el-icon-delete"
              :disabled="scope.row.id === id"
              @click="handleDelete(scope.row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
      style="text-align: right; margin-top: 20px"
      background
      :hide-on-single-page="true"
      :current-page="listSearch.page"
      :page-size="listSearch.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="listSearch.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 弹框组件 -->
    <vForm :vdialog="dialog" :vtitle="title" :visedit="isedit" :vformid="formid" @changeShow="showUpdate" />
  </div>
</template>

<script>
// 按钮吸顶
import Sticky from '@/components/Sticky/index'
// 按钮水波效果
import waves from '@/directive/waves/waves'
// 组件
import vForm from './components/form'
import { listUser, resetPassword, delUser, exportUserAll, exportUserCurrent } from '@/api/user'
import checkPermission from '@/utils/permission'
import { mapGetters } from 'vuex'

export default {
  components: { vForm, Sticky },
  directives: { waves },
  data() {
    return {
      url_api: process.env.VUE_APP_BASE_API,
      refreshLoading: false,
      downLoading: false,
      listLoading: true,
      list: [],
      listSearch: {
        total: 0,
        page: 1,
        pageSize: 10,
        ordering: '-date_joined',
        is_active: '',
        search: ''
      },
      enabledTypeOptions: [
        { key: 'true', display_name: '激活' },
        { key: 'false', display_name: '锁定' }
      ],
      // 弹出框定义属性
      // （与子组件的 props 属性一致）dialog 控制新增、编辑、查看弹窗的显示与隐藏
      dialog: false,
      title: '',
      isedit: '',
      formid: 0
      // 弹出框定义属性
    }
  },
  computed: {
    ...mapGetters([
      'id'
    ])
  },
  mounted() {
    this.getList()
  },
  methods: {
    // checkPermission 权限检查
    checkPermission,
    // 弹出框
    // 点击按钮事件，显示弹窗组件
    showAdd() {
      this.dialog = true
      this.title = '新增用户'
      this.isedit = 'add'
    },
    showEdit(row) {
      this.dialog = true
      this.title = '编辑用户'
      this.isedit = 'edit'
      this.formid = row
    },
    showView(row) {
      this.dialog = true
      this.title = '用户详情'
      this.isedit = 'view'
      this.formid = row
    },
    // 监听 子组件弹窗关闭后触发，由子组件调用
    showUpdate(val, valid) {
      if (val === 'false') {
        this.dialog = false
        this.formid = valid
      } else {
        this.dialog = true
      }
    },
    // 弹出框
    // 排序
    sortChange(column) {
      const { prop, order } = column
      if (order === 'descending') {
        this.listSearch.ordering = `-${prop}`
      } else {
        this.listSearch.ordering = prop
      }
      this.handleSearch()
    },
    // 排序
    // 搜索
    handleSearch() {
      // 当页面不在第一页时搜索内容报错
      this.listSearch.page = 1
      this.getList()
    },
    // 搜索
    // 密码重置
    setPassword(row) {
      this.$confirm('此操作将重置用户登陆密码为【 123456 】, 是否继续重置【 ' + row.username + ' 】用户密码？', '重置密码', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.listLoading = true
        resetPassword(row.id).then((res) => {
          this.listLoading = false
          this.$notify.success({
            type: 'success',
            title: '成功',
            message: res.message + '为【 123456 】   ( 请提醒用户尽快修改密码 )',
            showClose: true,
            duration: 5 * 1000
          })
        })
      }).catch(() => {
        this.$notify.info({
          type: 'info',
          title: '提示',
          message: '已取消重置',
          showClose: true,
          duration: 5 * 1000
        })
      })
    },
    // 密码重置
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将与有关联的数据一并删除, 是否继续删除【 ' + row.username + ' 】用户？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.listLoading = true
        delUser(row.id).then((res) => {
          this.listLoading = false
          this.$notify.success({
            type: 'success',
            title: '成功',
            message: '【 ' + row.username + ' 】用户已删除',
            showClose: true,
            duration: 5 * 1000
          })
          if (this.listSearch.total % 10 === 1) {
            if (this.listSearch.page !== 1) {
              this.listSearch.page = this.listSearch.page - 1
            }
          }
          this.getList()
        })
      }).catch(() => {
        this.$notify.info({
          type: 'info',
          title: '提示',
          message: '已取消删除',
          showClose: true,
          duration: 5 * 1000
        })
      })
    },
    // 删除
    // 导出
    handleDownloadCurrent() {
      this.downLoading = true
      exportUserCurrent(this.listSearch).then(res => {
        const url = this.url_api + 'media/export/' + res.data.name
        window.open(url)
        this.downLoading = false
        this.$notify.success({
          type: 'success',
          title: '成功',
          message: res.data.name + res.message,
          showClose: true,
          duration: 5 * 1000
        })
      })
    },
    handleDownloadAll() {
      this.downLoading = true
      exportUserAll().then(res => {
        const url = this.url_api + 'media/export/' + res.data.name
        window.open(url)
        this.downLoading = false
        this.$notify.success({
          type: 'success',
          title: '成功',
          message: res.data.name + res.message,
          showClose: true,
          duration: 5 * 1000
        })
      })
    },
    // 导出
    // 列表
    getList() {
      this.listLoading = true
      listUser(this.listSearch).then(res => {
        this.list = res.data
        this.listSearch.total = res.count
        this.listLoading = false
      })
    },
    // 列表
    // 分页
    handleSizeChange(val) {
      this.listSearch.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listSearch.page = val
      this.getList()
    },
    // 分页
    // 刷新
    refresh() {
      this.refreshLoading = true
      this.getList()
      this.refreshLoading = false
      this.$notify.info({
        type: 'info',
        title: '提示',
        message: '已刷新',
        showClose: true,
        duration: 5 * 1000
      })
    }
  }
}
</script>
